﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Infrastructure;
using WebApi.Model;

using Newtonsoft.Json.Linq;
using SqlSugar;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using HY.Model;
using System.Data.SqlTypes;
using Org.BouncyCastle.Asn1.X509;
using System.Runtime.CompilerServices;
using System.Reflection;

namespace WebApi.Controllers
{
    /// <summary>
    /// 自助服务机信息接口--self service machine
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SSMachineController : BaseController
    {
        SqlSugarScope db = DbHelper.GetDbConn();

        //private readonly ILogger<SSMachineController> _logger;

        public SSMachineController(ILogger<SSMachineController> logger) : base(logger)
        {
        }

        #region 01入厂刷身份证注册

        /// <summary>
        /// 新增入厂信息数据
        /// </summary>
        /// <param name="entity">入厂数据实体json</param>
        /// <returns></returns>
        [HttpPost("AddRegisterInfo")]
        public BackInfo AddRegisterInfo(RegisterInfo entity)
        {
            BackInfo bi = new BackInfo();
            bi.data = "";
            string msg = "";
            //01查询此IC卡号是否已经绑定过并且没有修改成出厂还卡--则将卡状态修改为0未使用状态
            //因为卡是循环使用的，还要判断这张卡是否正在绑定，需要先还了，相当于解绑，然后再操作。
            //只要是得到此卡号，一定是发卡机发出来的卡--上面操作是自动完成
            var db = DbHelper.GetDbConn();
            try
            {
                //忽略返回时间（ReturnTime）进行记录保存
                int affectedRow = db.Insertable(entity).IgnoreColumns("ReturnTime").ExecuteCommand(); //都是参数化实现
                if (affectedRow > 0)
                {
                    //2022-9-16 自助机不再维护图片表
                    ////铜粉的需要创建图片表，然后xyf使用
                    //if (entity.GoodsName == "铜粉")
                    //{
                    //    //创建图片记录--主要是处理铜粉的
                    //    CreatPicture(entity.Guid);
                    //}
                    bi.code = 200;
                    bi.message = "创建成功";
                    return bi;
                }
                else
                {
                    bi.code = 500;
                    bi.message = "创建失败";
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.message = "创建出错";
                LogToDB("RegisterInfo", "新增注册信息", JsonConvert.SerializeObject(entity), "出错", "SSMachineController-->AddRegisterInfo:创建注册记录出错" + ex.ToString());
                logger.ErrorModel($"{nameof(SSMachineController)}/{nameof(AddRegisterInfo)}", ex);
                return bi;
            }
        }


        ///// <summary>
        ///// 保存数据
        ///// </summary>
        ///// <param name="model"></param>
        ///// <param name="isInsert"></param>
        ///// <returns></returns>
        //private async Task<ReturnModel> Save(YPutOnRecord model, bool isInsert)
        //{
        //    try
        //    {
        //        if (model.Enable.Value)
        //        {
        //            GPutOnRecord gPutOnRecord = DbHelper.GPutOnRecord.GetFirst(it => it.GNumber == model.GNumber);
        //            List<YPutOnRecord> list = DbHelper.Db.Queryable<YPutOnRecord>().Where(it => it.GNumber == model.GNumber && it.Id != model.Id).Select(it => new YPutOnRecord { PlateList = it.PlateList, TotalWeight = SqlFunc.IsNull(it.TotalWeight, 0), RemainingWeight = SqlFunc.IsNull(it.RemainingWeight, 0), Enable = it.Enable }).ToList();
        //            //获取除该数据外其他启用状态的分配总额
        //            int allocatedWeight = list.Where(it => it.Enable == true).Sum(it => it.TotalWeight);
        //            //获取除该数据外其他未启用状态已使用的分配额
        //            int usedWeight = list.Where(it => it.Enable == true).Sum(it => it.TotalWeight - it.RemainingWeight.Value);
        //            if ((gPutOnRecord.TotalWeight - usedWeight) < (allocatedWeight + model.TotalWeight))
        //                return logger.Code_202("分配的运输重量大于购买备案号剩余可分配重量");

        //            model.PlateList = model.PlateList?.Replace('，', ',').Replace(" ", "");
        //            //以下判断购买备案号下属的运输备案号内，是否已使用过当前输入的车牌
        //            if (!string.IsNullOrWhiteSpace(model.PlateList))
        //            {
        //                string[] plateArray = list.Where(it => it.Enable == true).Select(it => it.PlateList).ToArray();
        //                if (plateArray.Length > 0)
        //                {
        //                    string plateString = "," + string.Join(",", plateArray) + ",";
        //                    string existPlate = string.Empty;
        //                    foreach (string plate in model.PlateList.Split(','))
        //                    {
        //                        if (plateString.Contains($",{plate},"))
        //                            existPlate += plate + ",";
        //                    }
        //                    if (!string.IsNullOrWhiteSpace(existPlate))
        //                        return logger.Code_202($"{existPlate.Trim(',')}在其他运输备案号已存在");
        //                }
        //            }
        //        }

        //        if (DbHelper.YPutOnRecord.IsAny(c => c.Id != model.Id && c.YNumber == model.YNumber))
        //            return logger.Code_202("运输备案号已存在");
        //        else if (isInsert)
        //            await DbHelper.RegisterInfo.InsertAsync(model);
        //        else
        //            await DbHelper.GetDbConn().Updateable(model).IgnoreColumns(it => it.CreatTime).ExecuteCommandAsync();
        //        LogToDB("YPutOnRecord", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
        //        return new ReturnModel { Count = 1 };
        //    }
        //    catch (Exception ex)
        //    {
        //        LogToDB("YPutOnRecord", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
        //        return logger.ErrorModel(nameof(YPutOnRecordController) + "-" + nameof(Save), ex);
        //    }
        //}



        /// <summary>
        /// 分页查询注册信息
        /// </summary>
        /// <param name="pageIndex">页号</param>
        /// <param name="pageSize">页数</param>
        /// <param name="ICardNum">IC卡号</param>
        /// <returns></returns>
        [HttpPost("QueryRegisterInfoByPage")]
        public BackInfo QueryRegisterInfoByPage([FromForm] int pageIndex, [FromForm] int pageSize, [FromForm] string ICardNum)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            bi.code = 500;
            int totalCount = 0;
            if (pageIndex == 0 || pageSize == 0)//默认
            {
                pageIndex = 1; // pageindex是从1开始的不是从零开始的
                pageSize = 20;
            }
            try
            {
                #region 查看备案信息下是否有此车辆可运输
                //还有一种方法，将所有条件写到一起，那么，如果通不过验证，则问题原因不好排查，并且条件修改麻烦
                //01 备案号是否存在
                var db = DbHelper.GetDbConn();//.OrderBy(st=>new {st.Id,st.Name})  ,OrderByType.Desc倒排
                var pageList = db.Queryable<RegisterInfo>().OrderBy(s=>s.ReceiveTime,OrderByType.Desc).ToPageList(pageIndex, pageSize, ref totalCount);
                if (pageList == null)
                {
                    bi.data = "";
                    bi.message = "未查询到未册信息";
                    bi.pageIndex = pageIndex;
                    bi.pageSize = pageSize;
                    bi.totalCount = 0;
                    return bi;
                }
                #endregion

                bi.code = 200;
                bi.data = pageList;
                bi.pageIndex = pageIndex;
                bi.pageSize = pageSize;
                bi.totalCount = totalCount;
                bi.message = "查询成功";
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                LogToDB("RegisterInfo", "查询注册信息", JsonConvert.SerializeObject(new { pageIndex = pageIndex, pageSize = pageSize, ICardNum= ICardNum }), "出错", "SSMachineController-->QueryRegisterInfoByPage:查询已经注册的信息出错：" + ex.ToString());
                logger.ErrorModel($"{nameof(SSMachineController)}/{nameof(QueryRegisterInfoByPage)}", ex);
                return bi;
            }
        }



        /// <summary>
        /// 检查此辆车是否有运输硫酸权限
        /// </summary>
        /// <param name="plate">车牌号</param> 
        /// <param name="strYNumber">备案号</param>
        /// <returns></returns>
        [HttpPost("CheckSulphuricAcid")]
        public BackInfo CheckSulphuricAcid([FromForm] string plate, [FromForm] string strYNumber)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            bi.code = 500;
            try
            {
                #region 查看备案信息下是否有此车辆可运输
                //还有一种方法，将所有条件写到一起，那么，如果通不过验证，则问题原因不好排查，并且条件修改麻烦
                //01 备案号是否存在
                var db = DbHelper.GetDbConn();
                PutOnRecord entity = db.Queryable<PutOnRecord>().First(it => it.YNumber == strYNumber);
                if (entity == null)
                {
                    bi.data = "1";
                    bi.message = "此备案号:" + strYNumber + " 不存在;";
                    return bi;
                }
                //02 备案号是否超期
                PutOnRecord entity2 = db.Queryable<PutOnRecord>().First(it => it.YNumber == strYNumber && it.StartDate <= System.DateTime.Now && it.EndDate >= System.DateTime.Now);
                if (entity2 == null)
                {
                    bi.data = "2";
                    bi.message = "此备案号:" + strYNumber + " 信息已经超期;";
                    return bi;
                }
                //03 此车辆是否在备案信息列表中
                PutOnRecord entity3 = db.Queryable<PutOnRecord>().First(it => it.YNumber == strYNumber && it.PlateList.Contains(plate));
                if (entity3 == null)
                {
                    bi.data = "3";
                    bi.message = "此车辆:" + plate + " 未登记在备案信息中;";
                    return bi;
                }
                //04 此车辆今日是否已经拉过
                PutOnRecord entity4 = db.Queryable<PutOnRecord>().First(it => it.YNumber == strYNumber && it.Today.Equals(DateTime.Now.Date) && it.TodayAreadyPlateList.Contains(plate));
                if (entity4 != null)
                {
                    bi.data = "3";
                    bi.message = "此车辆:" + plate + " 今日已经拉过不可再拉;";
                    return bi;
                }
                //PutOnRecord entity4 = db.Queryable<PutOnRecord>().First(it => it.YNumber == strYNumber && (it.Today != null && it.Today.Value.ToString("yyyy-MM-dd") == DateTime.Now.Date.ToString("yyyy-MM-dd"))) && it.TodayAreadyPlateList.Contains(plate));
                //if (entity4 == null)
                //{
                //    flag = false;
                //    data += "4,";
                //    msg += "此车辆:" + plate + " 今日已经拉过不可再拉;";
                //}
                #endregion
                bi.code = 200;
                bi.data = "";
                bi.message = "验证通过";
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "验证出错";
                LogToDB("RegisterInfo", "检查此辆车是否有运输硫酸权限", JsonConvert.SerializeObject(new { plate = plate, strYNumber = strYNumber }), "出错", "SSMachineController-->CheckSulphuricAcid:验证是否可以拉硫酸出错：" + ex.ToString());
                logger.ErrorModel($"{nameof(SSMachineController)}/{nameof(CheckSulphuricAcid)}", ex);
                return bi;
            }
        }

        /// <summary>
        /// 创建图片记录
        /// </summary>
        /// <param name="RegisterInfoGuid">注册信息guid</param>
        /// <returns></returns>
        [HttpPost("CreatPicture")]
        public BackInfo CreatPicture(string RegisterInfoGuid)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            string msg = "";
            try
            {
                //01 注册信息是否存在
                var db = DbHelper.GetDbConn();
                RegisterInfo entity = db.Queryable<RegisterInfo>().First(it => it.Guid == RegisterInfoGuid);
                if (entity == null)
                {
                    bi.code = 200;
                    bi.data = "1";
                    bi.message = "注册信息不存在,创建图片信息表记录失败;";
                    return bi;
                }
                //02 创建图片信息表记录 返回插入行数
                PictureModel insertObj = new PictureModel();
                //insertObj.RegisterInfoGuid = RegisterInfoGuid;
                int iExeCount = db.Insertable(insertObj).ExecuteCommand(); //都是参数化实现
                if (iExeCount == 1)
                {
                    bi.code = 200;
                    bi.data = "2";
                    bi.message = "创建成功";
                    return bi;
                }
                else
                {
                    bi.code = 500;
                    bi.data = "3";
                    bi.message = "创建失败";
                    //_logger.LogError("SSMachineController-->CreatPicture:创建图片记录失败" + msg);
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "4";
                bi.message = "创建出错";
                //_logger.LogError("SSMachineController-->CreatPicture:创建图片记录出错" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 查询流水信息
        /// </summary>
        /// <param name="lsh">流水号</param>
        /// <returns></returns>
        [HttpPost("QuerySerialNumber")]
        public BackInfo QuerySerialNumber(string lsh)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            string msg = "";
            try
            {
                bi.code = 200;
                RegisterInfo resultData = new RegisterInfo();
                //注册的信息为
                resultData.Id = 999;
                resultData.Value3 = "有信息";
                resultData.Value4 = "可以发卡";

                bi.data = resultData;
                bi.message = "创建失败";
                logger.LogError("SSMachineController-->CreatPicture:创建图片记录失败" + msg);
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "4";
                bi.message = "创建出错";
                logger.LogError("SSMachineController-->CreatPicture:创建图片记录出错" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 更新入厂信息的卡号
        /// </summary>
        /// <param name="regInfo">注册信息</param>
        /// <returns></returns>
        [HttpPost("UpdataRegisterInfo")]
        public BackInfo UpdataRegisterInfo(RegisterInfo regInfo)
        {
            BackInfo bi = new BackInfo();
            //先查出来，再进行更新
            using var db = DbHelper.GetDbConn();
            try
            {
                try
                {
                    string sql = "UPDATE t_RegisterInfo SET CardStatus=0,ReturnTime='" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE ICardNum='"+ regInfo.ICardNum + "' AND CardStatus=1";
                    var resultCount = db.Ado.ExecuteCommand(sql);
                    //LogToDB("RegisterInfo", "更新异常卡状态", sql, "异常", "存在因为异常而卡状态是入厂制卡的，将卡状态修改为0未使用状态");
                }
                catch (Exception ex)
                {
                    logger.ErrorModel("1更新异常卡状态" + $"{nameof(SSMachineController)}/{nameof(AddRegisterInfo)}", ex);
                }
                var data = db.Queryable<RegisterInfo>().Where(it => it.Guid == regInfo.Guid)
                   .First();
                if (data == null)
                {
                    logger.LogError("SSMachineController-->UpdataRegisterInfo:更新数据失败guid为:" + regInfo.Guid);
                    bi.code = 500;
                    bi.message = "更新数据失败";
                }
                data.CardStatus = 1;//制卡信息
                data.ICardNum = regInfo.ICardNum;//制卡信息
                //只更新某列
                int iExeCount = db.Updateable(data).UpdateColumns(it => new { it.ICardNum,it.CardStatus }).ExecuteCommand();
                if (iExeCount == 1)
                {
                    bi.code = 200;
                    bi.message = "更新卡号信息成功";
                }
                else
                {
                    logger.LogError("SSMachineController-->UpdataRegisterInfo:更新数据失败guid为:" + regInfo.Guid);
                    bi.code = 500;
                    bi.message = "更新数据失败";
                }
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.message = "创建出错";
                logger.LogError("SSMachineController-->UpdataRegisterInfo:更新数据失败出错" + ex.ToString());
                return bi;
            }
        }


        #endregion

        #region 02出厂还卡

        //先刷卡查询数据本条数据

        /// <summary>
        /// 出厂还卡
        /// </summary>
        /// <param name="regInfo">注册信息</param>
        /// <returns></returns>
        [HttpPost("BackICard")]
        public BackInfo BackICard(RegisterInfo regInfo)
        {
            BackInfo bi = new BackInfo();
            try
            {
                bi.data = "";
                var db = DbHelper.GetDbConn();
                RegisterInfo temp = db.Queryable<RegisterInfo>().Where(it => it.Guid == regInfo.Guid).First();
                if (temp != null)
                {
                    //将卡状态修改为: 2出厂已归还
                    temp.CardStatus = 2;
                    temp.ReturnTime = System.DateTime.Now;
                    int result = db.Updateable(temp).UpdateColumns(it => new { it.ReturnTime, it.CardStatus }).ExecuteCommand();
                    if (result > 0)
                    {
                        bi.code = 200;
                        bi.message = "还卡成功";
                        //还卡成功，则判断是否更新基础数据
                        //UpdataBase(temp.GoodsName, temp.Company, temp.Revicer);
                        return bi;
                    }
                    else
                    {
                        bi.code = 500;
                        bi.message = "还卡失败";
                        return bi;
                    }
                }
                else
                {
                    bi.code = 500;
                    bi.message = "还卡失败,无此卡:" + regInfo.ICardNum + "注册信息";
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.message = "还卡出错";
                logger.LogError("SSMachineController-->BackICard:还卡失败出错" + ex.ToString());
                return bi;
            }
        }
        /// <summary>
        /// 没有此信息则更新基础信息
        /// </summary>
        /// <param name="Product">货物</param>
        /// <param name="Sender">发货单位</param>
        /// <param name="Receiver">收货单位</param>
        /// <param name="CustomType">客户类型</param>
        private void UpdataBase(string Product, string Sender, string Receiver,string CustomType )
        {
            try
            {
                string msg = "";
                #region 【自助机还卡自动保存】货物名
                if (!string.IsNullOrEmpty(Product) && Product != "多种货物")
                {
                    //查询数据是否存在
                    var db = DbHelper.GetDbConn();
                    List<ProductList> listResult = db.Queryable<ProductList>()
                        .Where(it => it.product == Product)
                        .ToList();
                    if (listResult == null || listResult.Count == 0)
                    {
                        //无则新增
                        ProductList insertObj = new ProductList();
                        insertObj.product = Product;
                        insertObj.code = Product;
                        int iExeCount = db.Insertable(insertObj).ExecuteCommand();               
                        if (iExeCount == 1)
                        {
                            msg += "【自助机还卡自动保存】货物名字:" + Product;
                        }
                    }
                }
                #endregion

                #region 【自助机还卡自动保存】发货单位
                if (!string.IsNullOrEmpty(Sender))
                {
                    //查询数据是否存在
                    var db = DbHelper.GetDbConn();
                    List<SenderList> listResult = db.Queryable<SenderList>()
                        .Where(it => it.sender == Sender)
                        .ToList();
                    if (listResult == null || listResult.Count == 0)
                    {
                        //无则新增
                        SenderList insertObj = new SenderList();
                        insertObj.sender = Sender;
                        int iExeCount = db.Insertable(insertObj).ExecuteCommand();                
                        if (iExeCount == 1)
                        {
                            msg += "【自助机还卡自动保存】发货单位:" + Sender;
                        }
                    }
                    else
                    {
                        //有则判断更新客户类型
                        if (!string.IsNullOrEmpty(CustomType) && listResult.Count == 1)
                        {
                            //更新客户类型为最新
                            CustomType = System.Text.RegularExpressions.Regex.Replace(CustomType, @"[\r\n]", "");    // 注意是：\r\n
                            CustomType = CustomType.Replace(" ", "");
                            var data = db.Queryable<SenderList>().Where(it => it.sender == Sender)
                                               .First();
                            if (data != null && data.remarktext != CustomType)
                            {
                                string oldCustomType = data.remarktext;
                                data.remarktext = CustomType;
                                int iExeCount = db.Updateable(data).UpdateColumns(it => new { it.remarktext }).ExecuteCommand();
                                if (iExeCount == 1)//记录日志信息
                                {
                                    LogToDB("SenderList", "更新客户类型", "", "成功", $"将原客户类型：{oldCustomType}更新为过车数据中的客户类型{CustomType}");
                                }
                                else
                                {
                                    LogToDB("SenderList", "更新客户类型", "", "失败", $"将原客户类型：{oldCustomType}更新为过车数据中的客户类型{CustomType}");
                                }
                            }
                        }
                    }
                }
                #endregion

                #region 【自助机还卡自动保存】收货单位
                if (!string.IsNullOrEmpty(Receiver))
                {
                    //查询数据是否存在
                    var db = DbHelper.GetDbConn();
                    List<ReceiverList> listResult = db.Queryable<ReceiverList>()
                        .Where(it => it.receiver == Receiver)
                        .ToList();
                    if (listResult == null || listResult.Count == 0)
                    {
                        //无则新增
                        ReceiverList insertObj = new ReceiverList();
                        insertObj.receiver = Receiver;
                        int iExeCount = db.Insertable(insertObj).ExecuteCommand();
                        if (iExeCount == 1)
                        {
                            msg += "【自助机还卡自动保存】收货单位:" + Receiver;
                        }
                    }
                }
                #endregion

                //将操作记录保存进日志文件中
                if (msg != "")
                {
                    LogToDB("基础信息", "自助机还卡自动保存基础信息", JsonConvert.SerializeObject(new { Product = Product, Receiver = Receiver, Sender = Sender }), "成功", "SSMachineController-->UpdataBase:" + msg);
                }
            }
            catch (Exception ex)
            {
                logger.LogError("SSMachineController-->UpdataBase:" + ex.ToString());
            }
        }


        /// <summary>
        /// 根据IC卡号查找当前已经注册的信息
        /// </summary>
        /// <param name="CardNum">卡号</param>
        /// <returns></returns>
        [HttpPost("QueryRegisterInfoByCardNum")]
        public BackInfo QueryRegisterInfoByCardNum(string CardNum)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            try
            {
                bi.code = 200;
                RegisterInfo resultData = new RegisterInfo();

                var db = DbHelper.GetDbConn();//(st,sc)=>sc.Id,OrderByType.Desc
                //查询卡状态为1【入厂录入信息】
                RegisterInfo entity = db.Queryable<RegisterInfo>().OrderBy((re) => re.ReceiveTime, OrderByType.Desc).First(it => it.ICardNum == CardNum && it.CardStatus == 1);
                if (entity != null)
                {
                    bi.code = 200;
                    bi.data = entity;
                    bi.message = "查询成功";
                    return bi;
                }
                else
                {
                    bi.code = 500;
                    bi.data = "";
                    bi.message = "不存在该卡号的入厂信息";
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryRegisterInfoByCardNum:查询卡号信息出错" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 根据IC卡号查找此卡是否归还
        /// </summary>
        /// <param name="CardNum">卡号</param>
        /// <returns></returns>
        [HttpPost("QueryBackByCardNum")]
        public BackInfo QueryBackByCardNum([FromForm] string CardNum)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            try
            {
                bi.code = 200;
                var db = DbHelper.GetDbConn();
                //是否存在已经注册的记录 is exists
                bool isExists = db.Queryable<RegisterInfo>().Where(it => it.CardStatus == 1 && it.ICardNum == CardNum).Any();
                if (isExists)
                {
                    bi.code = 200;
                    bi.data = 1;
                    bi.message = "存在";
                    return bi;
                }
                else
                {
                    bi.code = 200;
                    bi.data = 0;
                    bi.message = "不存在";
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryBackByCardNum:查询卡号注册信息出错" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 根据IC卡号查找此卡是否完成称重
        /// </summary>
        /// <param name="CardNum">卡号</param>
        /// <returns></returns>
        [HttpPost("BackICardByCardNum")]
        public BackInfo BackICardByCardNum([FromForm] string CardNum)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            try
            {
                bi.code = 200;
                var db = DbHelper.GetDbConn();
                //根据卡号 按发卡时间查找最新一条数据
                //bool isExists = db.Queryable<RegisterInfo>().Where(it => it.CardStatus == 1 && it.ICardNum == CardNum).Any();
                RegisterInfo entity = db.Queryable<RegisterInfo>().OrderBy(it=>it.ReceiveTime,OrderByType.Desc).First(it => it.ICardNum == CardNum);
                #region 卡状态不对的卡不能进行还卡操作
                if (entity == null)
                {
                    bi.code = 201;
                    bi.data = "1";
                    bi.message = "未识别的卡,不能进行还卡";
                    return bi;
                }
                if (entity.CardStatus != 1)
                {
                    switch (entity.CardStatus)//都是有问题的，没有走正常流程，故不能还卡
                    {
                        case -1:
                            bi.code = 201;
                            bi.data = "1";
                            bi.message = "此卡禁用,不能还卡";
                            return bi;
                        case 2:
                            bi.code = 201;
                            bi.data = "1";
                            bi.message = "已归还的卡,不能重复还卡";
                            return bi;
                        case 0:
                            bi.code = 201;
                            bi.data = "10";
                            bi.message = "此卡未启用,直接还卡,不打印出门证";
                            return bi;
                    }
                }
                #endregion
                entity.CardStatus = 2;
                entity.ReturnTime = System.DateTime.Now;

                #region 多种货物卡还卡
                if (entity.GoodsName == "多种货物")
                {
                    List<WeightRecord> ListData1 = db.Queryable<WeightRecord>().Where(it => it.Guid == entity.Guid)
                    .OrderBy(it => new { it.CreateTime }, OrderByType.Desc)//用CreateTime排序，用称重时间字段可能为空
                    .ToList();
                    if (ListData1 != null && ListData1.Count > 0)
                    {
                        //多种货物由于不知道一共有多少种货物，
                        //故只要在过车重量记录表【t_WeightRecord】里最新一条完成称重，就认为已经完成
                        if (ListData1[0].IsComplete == 1)
                        {
                            //修改注册信息卡状态
                            entity.CardStatus = 2;
                            entity.ReturnTime = System.DateTime.Now;
                            int result = db.Updateable(entity).UpdateColumns(it => new { it.ReturnTime, it.CardStatus }).ExecuteCommand();
                            if (result > 0)
                            {
                                bi.code = 200;
                                bi.data = JsonConvert.SerializeObject(new { ResultCode = 2, IdentityNum = entity.IdentityNum, RegName = entity.RegName, Plate = entity.Plate });
                                bi.message = "此卡已经完成称重,可以还卡,收回到卡槽";
                                //还卡成功，则判断是否更新基础数据
                                UpdataBase(ListData1[0].GoodsName, ListData1[0].SendCptName, ListData1[0].ReceiveCptName, ListData1[0].Predefined2);
                            }
                            else
                            {
                                bi.code = 201;
                                bi.data = "3";
                                bi.message = "此卡已经完成称重,可以还卡,收回到卡槽,但更新数据库卡注册信息失败";
                                //保存数据库
                            }
                            return bi;
                        }
                        else
                        {
                            bi.code = 201;
                            bi.data = "4";
                            bi.message = "此卡未完成称重,不能还卡,卡重新从卡槽吐出";
                            return bi;
                        }
                    }
                    else
                    {
                        bi.code = 201;
                        bi.data = "5";
                        bi.message = "此卡没有过车记录,直接还卡,不打印出门证";
                        return bi;
                    }
                }
                #endregion

                #region 其他货物
                //看是卡信息是否是厂内流转货物，厂内流转货物直接还卡
                if (entity.CardType == 3)
                {
                    bi.code = 201;
                    bi.data = "6";
                    bi.message = "卡信息是厂内流转货物,直接还卡,不打印出门证";
                    int result = db.Updateable(entity).UpdateColumns(it => new { it.ReturnTime, it.CardStatus }).ExecuteCommand();
                    UpdataBase(entity.GoodsName, entity.Company, entity.Revicer, "");
                    return bi;
                }

                //再查询是否有记录
                List<WeightRecord> ListData = db.Queryable<WeightRecord>().Where(it => it.Guid == entity.Guid)
                    .OrderBy(it => new { it.CreateTime }, OrderByType.Desc)//用CreateTime排序，用称重时间字段可能为空
                    .ToList();
                if (ListData != null && ListData.Count > 0)
                {
                    //故只要在过车重量记录表【t_WeightRecord】里最新一条完成称重，就认为已经完成
                    if (ListData[0].IsComplete == 1)
                    {
                        //修改注册信息卡状态
                        entity.CardStatus = 2;
                        entity.ReturnTime = System.DateTime.Now;
                        int result = db.Updateable(entity).UpdateColumns(it => new { it.ReturnTime, it.CardStatus }).ExecuteCommand();
                        if (result > 0)
                        {
                            bi.code = 200;
                            bi.data = JsonConvert.SerializeObject(new { ResultCode = 2, IdentityNum = entity.IdentityNum, RegName = entity.RegName, Plate = entity.Plate });
                            bi.message = "此卡已经完成称重,可以还卡";
                            //还卡成功，则判断是否更新基础数据
                            UpdataBase(ListData[0].GoodsName, ListData[0].SendCptName, ListData[0].ReceiveCptName, ListData[0].Predefined2);
                        }
                        else
                        {
                            bi.code = 201;
                            bi.data = "3";
                            bi.message = "此卡已经完成称重,可以还卡,收回到卡槽,但更新数据库卡注册信息失败";
                            //保存数据库
                        }
                        return bi;
                    }
                    else
                    {
                        bi.code = 201;
                        bi.data = "8";
                        bi.message = "此卡未完成称重,不能还卡";
                        return bi;
                    }
                }
                else
                {
                    bi.code = 201;
                    bi.data = "9";
                    bi.message = "此卡没有过车记录,直接还卡,不打印出门证";
                    //直接更新
                    db.Updateable(entity).UpdateColumns(it => new { it.ReturnTime, it.CardStatus }).ExecuteCommand();

                    return bi;
                }
                #endregion
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryBackByCardNum:查询卡号注册信息出错" + ex.ToString());
                return bi;
            }
        }




        #endregion


        #region 03数据展示相关接口
        //--门卫数据展示

        /// <summary>
        /// 门卫信息展示数据查询
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns></returns>
        [HttpPost("QueryToGuardOffice")]
        public BackInfo QueryToGuardOffice([FromForm] string date)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            try
            {
                bi.code = 200;
                RegisterInfo resultData = new RegisterInfo();
                DateTime dtNow = Convert.ToDateTime(date);
                var db = DbHelper.GetDbConn();
                //查询卡状态为1【入厂录入信息】
                List<RegisterInfo> ListData = db.Queryable<RegisterInfo>().Where(it => it.ReceiveTime.Date.Equals(dtNow.Date) && (it.CardStatus == 1 || it.CardStatus == 2) && it.CardType != 3)
                    .OrderBy(it => new { it.ReceiveTime, it.ReturnTime}, OrderByType.Desc)
                    .ToList();
                if (ListData != null)
                {
                    bi.code = 200;
                    bi.data = ListData;
                    bi.message = "查询成功";
                    return bi;
                }
                else
                {
                    bi.code = 500;
                    bi.data = "";
                    bi.message = "没有查询到相应数据";
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryBackByCardNum:查询卡号注册信息出错" + ex.ToString());
                return bi;
            }
        }





        /// <summary>
        /// 门卫信息展示----查询当天的称重数据
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns></returns>
        [HttpPost("QueryWeightRecord_ToGuardOffice")]
        public BackInfo QueryWeightRecord_ToGuardOffice([FromForm] string date)
        {
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            //判断日期参数格式
            DateTime dt1 = DateTime.Now;
            if (!DateTime.TryParse(date, out dt1))
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "日期参数据格式不正确！";
                return bi;
            };
            try
            {
                bi.code = 200;
                RegisterInfo resultData = new RegisterInfo();
                DateTime dtNow = Convert.ToDateTime(date);
                var db = DbHelper.GetDbConn();
                //查询卡状态为1【入厂录入信息】
                //--语句分析：查询毛重时间或皮重时间在当天时间范围内的数据
                //SELECT Id,Guid,RecordId,ScaleCode,ScaleFlag,TruckNum,GrossTime,TareTime,IsComplete,GoodsName,DriverName,SendCptName,ReceiveCptName from t_WeightRecord where (CardType is not null and CardType!=3 ) and (((GrossTime is not null and GrossTime > '2023-07-14 00:00:00' and GrossTime<'2023-07-14 23:59:59') or(GrossTime is null and (TareTime is not null and TareTime > '2023-07-14 00:00:00' and TareTime < '2023-07-14 23:59:59'))) or((TareTime is not null and TareTime > '2023-07-14 00:00:00' and TareTime < '2023-07-14 23:59:59') or(TareTime is null and (GrossTime is not null and GrossTime > '2023-07-14 00:00:00' and GrossTime < '2023-07-14 23:59:59')))) order by id desc
                string sql = "SELECT Id,Guid,RecordId,ScaleCode,ScaleFlag,TruckNum,GrossTime,TareTime,IsComplete,GoodsName,DriverName,SendCptName,ReceiveCptName from t_WeightRecord where (CardType is not null and CardType!=3 ) and (((GrossTime is not null and GrossTime > '{0}' and GrossTime<'{1}') or(GrossTime is null and (TareTime is not null and TareTime > '{0}' and TareTime < '{1}'))) or((TareTime is not null and TareTime > '{0}' and TareTime < '{1}') or(TareTime is null and (GrossTime is not null and GrossTime > '{0}' and GrossTime < '{1}')))) order by id desc ";
                sql = string.Format(sql, dt1.ToString("yyyy-MM-dd 00:00:00"), dt1.ToString("yyyy-MM-dd 23:59:59"));
                List<WeightRecord> ListData = DbHelper.GetDbConn().Ado.SqlQuery<WeightRecord>(sql);
                if (ListData != null)
                {
                    bi.code = 200;
                    bi.data = ListData;
                    bi.message = "查询成功";
                    return bi;
                }
                else
                {
                    bi.code = 500;
                    bi.data = "";
                    bi.message = "没有查询到相应数据";
                    return bi;
                }
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryBackByCardNum:查询卡号注册信息出错" + ex.ToString());
                return bi;
            }
        }


        

        #endregion

        //RegisterInfo
        #region 04注册数据展示
        //--门卫数据展示

        /// <summary>
        /// 门卫信息展示数据查询
        /// </summary>
        /// <param name="ParameterDic">查询字段参数</param>
        /// <returns></returns>
        [HttpPost("QueryRegByParameter")]
        public BackInfo QueryRegByParameter(QueryParameter ParameterDic)
        {
            string json1=JsonConvert.SerializeObject(ParameterDic);
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            //查询语句//提示数据量过大，请缩小导出数据范围
            try
            {
                string strGoodsName = "";
                string strCompany = "";
                string strReceiver = "";
                DateTime ReceiveTimeStart = Convert.ToDateTime(ParameterDic.ParameterDic["ReceiveTimeStart"]);
                DateTime ReceiveTimeEnd = Convert.ToDateTime(ParameterDic.ParameterDic["ReceiveTimeEnd"]);
                #region 查询条件
                if (ParameterDic != null && ParameterDic.ParameterDic != null)
                {
                    foreach (var item in ParameterDic.ParameterDic)
                    {
                        switch (item.Key)
                        {
                            case "GoodsName":
                                strGoodsName= item.Value;
                                break;
                            case "Sender":
                                strCompany = item.Value;
                                break;
                            case "Receiver":
                                strReceiver = item.Value;
                                break;
                        }
                    }
                }
                #endregion

                int pagenumber = 1; // pagenumber是从1开始的不是从零开始的
                int pageSize = 20;
                int totalCount = 0;

                //页号
                int pageIndex = 1;

                //1.厂内流转的不还卡，故一个卡对应多条记录，故不进行门卫查询数据
                var list = db.Queryable<RegisterInfo>()
                    .LeftJoin<WeightRecord>((ri, wr) => ri.Guid == wr.Guid
                    && ((wr.GoodsName != null && wr.GoodsName.Contains(strGoodsName)) || (ri.GoodsName != null && ri.GoodsName.Contains(strGoodsName))
                    //&& ((wr.SendCptName != null && wr.SendCptName.Contains(strCompany)) || (ri.Company != null && ri.Company.Contains(strCompany)))
                    ))
                //)
                .Where(ri => (ri.CardType == 1 || ri.CardType == 2) && ri.ReceiveTime >= ReceiveTimeStart && ri.ReceiveTime <= ReceiveTimeEnd && (ri.Revicer != null && ri.Revicer.Contains(strReceiver)))
                .Select((ri, wr) => new
                {
                    Id = ri.Id,
                    ICardNum = ri.ICardNum,
                    RegName = ri.RegName,
                    IdentityNum = ri.IdentityNum,
                    Company = ri.Company,
                    ReceiveTime = ri.ReceiveTime,
                    ReturnTime = ri.ReturnTime,
                    GoodsName = ri.GoodsName,
                    CardStatus = ri.CardStatus,
                    Guid = ri.Guid,
                    Plate = ri.Plate,
                    Revicer = ri.Revicer,
                    RegPhone = ri.RegPhone,
                    DriverName2 = ri.DriverName2,
                    DriverPhone2 = ri.DriverPhone2,
                    CardType = ri.CardType,
                    Value3 = ri.Value3,//住址
                    GrossWeight = wr.GrossWeight,
                    GrossTime = wr.GrossTime,
                    TareWeight = wr.TareWeight,
                    TareTime = wr.TareTime,
                    NetWeight = wr.NetWeight,
                    //发货单位、货物名称，
                    SendCptName = wr.SendCptName,
                    MultipleGoodsName = wr.GoodsName//当为【多种货物】时需要将集控保存的货名查询出来                    
                })
                .ToPageList(pageIndex, pageSize, ref totalCount);
                bi.data = list;
                bi.code = 200;
                bi.message = "查询成功";
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryRegByParameter:查询过车信息" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 门卫信息展示数据查询--只查注册信息
        /// </summary>
        /// <param name="ParameterDic">查询字段参数</param>
        /// <returns></returns>
        [HttpPost("QueryOnlyRegByParameter")]
        public BackInfo QueryOnlyRegByParameter(QueryParameter ParameterDic)
        {
            string json1 = JsonConvert.SerializeObject(ParameterDic);
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            //查询语句//提示数据量过大，请缩小导出数据范围
            try
            {
                string strGoodsName = "";
                string strCompany = "";
                string strReceiver = "";
                DateTime ReceiveTimeStart = Convert.ToDateTime(ParameterDic.ParameterDic["ReceiveTimeStart"]);
                DateTime ReceiveTimeEnd = Convert.ToDateTime(ParameterDic.ParameterDic["ReceiveTimeEnd"]);
                string ExportFlag = ParameterDic.ParameterDic["Export"];
                #region 查询条件
                if (ParameterDic != null && ParameterDic.ParameterDic != null)
                {
                    foreach (var item in ParameterDic.ParameterDic)
                    {
                        switch (item.Key)
                        {
                            case "GoodsName":
                                strGoodsName = item.Value;
                                break;
                            case "Sender":
                                strCompany = item.Value;
                                break;
                            case "Receiver":
                                strReceiver = item.Value;
                                break;
                        }
                    }
                }
                #endregion
                //int pagenumber = 1; // pagenumber是从1开始的不是从零开始的 在查询语法中
                int pageSize = 20;
                int totalCount = 0;
                int pageIndex = 1;
                int totalNumber = 0;
                //、、int pageNumber, int pageSize, ref int totalNumber, ref int totalPage
                //页号
                if (ParameterDic != null && ParameterDic.pageIndex != 0)
                {
                    pageIndex = ParameterDic.pageIndex + 1;//因为页从1开始
                }

                //页大小
                if (ParameterDic != null && ParameterDic.pageSize != 0)
                {
                    pageSize = ParameterDic.pageSize;
                }

                //1.厂内流转的不还卡，故一个卡对应多条记录，故不进行门卫查询数据
                List<RegisterInfo> list;
                if (ExportFlag == "导出")
                {
                    list = db.Queryable<RegisterInfo>()
                    .Where(ri => (ri.CardType == 1 || ri.CardType == 2) &&
                    ri.ReceiveTime >= ReceiveTimeStart &&
                    ri.ReceiveTime <= ReceiveTimeEnd &&
                    (ri.Revicer != null && ri.Revicer.Contains(strReceiver)) &&
                    (ri.GoodsName != null && ri.GoodsName.Contains(strGoodsName)))
                    .ToPageList(pageIndex, int.MaxValue, ref totalNumber, ref totalCount);//页大小为最大值
                }
                else
                {
                    list = db.Queryable<RegisterInfo>()
                    .Where(ri => (ri.CardType == 1 || ri.CardType == 2) &&
                    ri.ReceiveTime >= ReceiveTimeStart &&
                    ri.ReceiveTime <= ReceiveTimeEnd &&
                    (ri.Revicer != null && ri.Revicer.Contains(strReceiver)) &&
                    (ri.GoodsName != null && ri.GoodsName.Contains(strGoodsName)))
                    .ToPageList(pageIndex, pageSize, ref totalNumber, ref totalCount);
                }

                bi.data = list;
                bi.code = 200;
                bi.pageIndex = pageIndex;
                bi.pageSize = pageSize;
                bi.totalCount = totalCount;
                bi.message = "查询成功";
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.pageIndex = 0;
                bi.pageSize = 20;
                bi.totalCount = 0;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryRegByParameter:查询过车信息" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 门卫信息展示数据查询--查询称重记录的注册信息
        /// </summary>
        /// <param name="ParameterDic">查询字段参数</param>
        /// <returns></returns>
        [HttpPost("QueryScaleRegByParameter")]
        public BackInfo QueryScaleRegByParameter(QueryParameter ParameterDic)
        {
            //查询两次数据库：
            //1.先查询符合条件的称重记录
            //2.再用in语句查询所有注册信息--带分页的

            //SELECT Id,Guid,RecordId,ScaleCode,ScaleFlag,TruckNum,GrossTime,TareTime,IsComplete,GoodsName,DriverName,SendCptName,ReceiveCptName 

            /*
             SELECT Guid from t_WeightRecord 
where (CardType is not null and CardType!=3 ) and 
(((GrossTime is not null and GrossTime > '2023-07-14 00:00:00' and GrossTime<'2023-07-14 23:59:59') or(GrossTime is null and (TareTime is not null and TareTime > '2023-07-14 00:00:00' and TareTime < '2023-07-14 23:59:59'))) or((TareTime is not null and TareTime > '2023-07-14 00:00:00' and TareTime < '2023-07-14 23:59:59') or(TareTime is null and (GrossTime is not null and GrossTime > '2023-07-14 00:00:00' and GrossTime < '2023-07-14 23:59:59'))))
--and GoodsName = '' 
--and SendCptName
--and ReceiveCptName=''

             */
            BackInfo bi = new BackInfo();

            //
            DateTime ReceiveTimeStart = DateTime.Now;
            DateTime ReceiveTimeEnd = DateTime.Now;
            #region 判断日期参数格式
            if (!DateTime.TryParse(ParameterDic.ParameterDic["ReceiveTimeStart"], out ReceiveTimeStart))
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "日期参数据格式不正确！";
                return bi;
            };
            if (!DateTime.TryParse(ParameterDic.ParameterDic["ReceiveTimeEnd"], out ReceiveTimeEnd))
            {
                bi.code = 500;
                bi.data = "";
                bi.message = "日期参数据格式不正确！";
                return bi;
            };
            #endregion

            string sql_wr = "SELECT Guid from t_WeightRecord where (CardType is not null and CardType!=3 ) and ";
            string sql_wr2 = string.Format("(((GrossTime is not null and GrossTime > '{0}' and GrossTime<'{1}') or(GrossTime is null and (TareTime is not null and TareTime > '{0}' and TareTime < '{1}'))) or((TareTime is not null and TareTime > '{0}' and TareTime < '{1}') or(TareTime is null and (GrossTime is not null and GrossTime > '{0}' and GrossTime < '{1}'))))",ReceiveTimeStart.ToString("yyyy-MM-dd HH:mm:ss"), ReceiveTimeEnd.ToString("yyyy-MM-dd HH:mm:ss"));
            sql_wr = sql_wr + sql_wr2;

            string json1 = JsonConvert.SerializeObject(ParameterDic);
            var jsn = new JObject();
            
            //查询语句//提示数据量过大，请缩小导出数据范围
            try
            {
                string strGoodsName = "";
                string strCompany = "";
                string strReceiver = "";
                string strScale = "";
                //DateTime ReceiveTimeStart = Convert.ToDateTime(ParameterDic.ParameterDic["ReceiveTimeStart"]);
                //DateTime ReceiveTimeEnd = Convert.ToDateTime(ParameterDic.ParameterDic["ReceiveTimeEnd"]);
                string ExportFlag = ParameterDic.ParameterDic["Export"];
                #region 查询条件
                if (ParameterDic != null && ParameterDic.ParameterDic != null)
                {
                    foreach (var item in ParameterDic.ParameterDic)
                    {
                        switch (item.Key)
                        {
                            case "GoodsName":                                
                                strGoodsName = item.Value;
                                sql_wr += $" and GoodsName = '{strGoodsName}' ";
                                break;
                            case "Sender":
                                strCompany = item.Value;
                                sql_wr += $" and SendCptName = '{strCompany}' ";
                                break;
                            case "Receiver":
                                strReceiver = item.Value;
                                sql_wr += $" and ReceiveCptName = '{strReceiver}' ";
                                break;
                            case "Scale":
                                strScale = item.Value;
                                if (!string.IsNullOrEmpty(strScale))
                                {
                                    sql_wr += DealScaleParameter(strScale);
                                }
                                else
                                {
                                    //秤台号参数为空，则说明查询所有全部，则直接查询注册信息表 [t_RegisterInfo]
                                }
                                break;
                        }
                    }
                    //添加上分组，避免称重多次，查询出来多条注册信息
                    sql_wr += " group by Guid";
                }
                #endregion
                //int pagenumber = 1; // pagenumber是从1开始的不是从零开始的 在查询语法中
                int pageSize = 20;
                int totalCount = 0;
                int pageIndex = 1;
                int totalNumber = 0;
                //、、int pageNumber, int pageSize, ref int totalNumber, ref int totalPage
                //页号
                if (ParameterDic != null && ParameterDic.pageIndex != 0)
                {
                    pageIndex = ParameterDic.pageIndex + 1;//因为页从1开始
                }

                //页大小
                if (ParameterDic != null && ParameterDic.pageSize != 0)
                {
                    pageSize = ParameterDic.pageSize;
                }

                //1.厂内流转的不还卡，故一个卡对应多条记录，故不进行门卫查询数据
                List<RegisterInfo> list;
                if (ExportFlag == "导出")
                {
                    if (!string.IsNullOrEmpty(strScale))
                    {
                        list = db.SqlQueryable<RegisterInfo>($"select * from  t_RegisterInfo where Guid in ({sql_wr}) ")
                        .OrderBy("Id desc")
                        .ToPageList(pageIndex, int.MaxValue, ref totalNumber, ref totalCount);//页大小为最大值                        
                    }
                    else
                    {
                        list = db.Queryable<RegisterInfo>()
                        .Where(ri => (ri.CardType == 1 || ri.CardType == 2) &&
                        ri.ReceiveTime >= ReceiveTimeStart &&
                        ri.ReceiveTime <= ReceiveTimeEnd &&
                        (ri.Revicer != null && ri.Revicer.Contains(strReceiver)) &&
                        (ri.GoodsName != null && ri.GoodsName.Contains(strGoodsName)))
                        .ToPageList(pageIndex, int.MaxValue, ref totalNumber, ref totalCount);//页大小为最大值
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(strScale))
                    {
                        list = db.SqlQueryable<RegisterInfo>($"select * from  t_RegisterInfo where Guid in ({sql_wr}) ")
                        .OrderBy("Id desc")
                        .ToPageList(pageIndex, pageSize, ref totalNumber, ref totalCount); //页大小为最大值
                    }
                    else
                    {
                        list = db.Queryable<RegisterInfo>()
                        .Where(ri => (ri.CardType == 1 || ri.CardType == 2) &&
                        ri.ReceiveTime >= ReceiveTimeStart &&
                        ri.ReceiveTime <= ReceiveTimeEnd &&
                        (ri.Revicer != null && ri.Revicer.Contains(strReceiver)) &&
                        (ri.GoodsName != null && ri.GoodsName.Contains(strGoodsName)))
                        .ToPageList(pageIndex, pageSize, ref totalNumber, ref totalCount);
                    }                    
                }

                bi.data = list;
                bi.code = 200;
                bi.pageIndex = pageIndex;
                bi.pageSize = pageSize;
                bi.totalCount = totalCount;
                bi.message = "查询成功";
                return bi;
            }
            catch (Exception ex)
            {
                bi.code = 500;
                bi.pageIndex = 0;
                bi.pageSize = 20;
                bi.totalCount = 0;
                bi.data = "";
                bi.message = "查询出错";
                logger.LogError("SSMachineController-->QueryRegByParameter:查询过车信息" + ex.ToString());
                return bi;
            }
        }
        /// <summary>
        /// 处理秤台号 转为sql
        /// </summary>
        /// <param name="scaleStr"></param>
        /// <returns></returns>
        private string DealScaleParameter(string scaleStr)
        {
            try
            {
                string str = "";
                if (!string.IsNullOrEmpty(scaleStr))
                {
                    var sacleList = scaleStr.Split(',');
                    if (sacleList !=null && sacleList.Length != 0)
                    {
                        for (int i = 0; i < sacleList.Length; i++)
                        {
                            if (i == 0)
                            {
                                str += $" and (RecordId like '{sacleList[i]}%' ";
                            }
                            else
                            {
                                str += $" or RecordId like '{sacleList[i]}%' ";
                            }
                        }
                        //添加最后半个括号
                        if (str.Length != 0)
                        {
                            str += ") ";
                        }
                    }
                }
                return str;
            }
            catch (Exception ex)
            {
                logger.LogError("SSMachineController-->DealScaleParameter:查询过车信息" + ex.ToString());
                return "";
            }
        }

        #endregion


        #region 05运输备案号信息操作
        /// <summary>
        /// 根据车牌号及收货单位查询备案号信息--注掉不用了 不加运输单位判断
        /// </summary>
        /// <param name="plate">车牌号</param> 
        /// <param name="strGCompany">购买单位（即收货单位）</param>
        /// <param name="strYCompany">运输单位</param>
        /// <returns></returns>
        [HttpPost("CheckSulphuricAcidByInfo1")]
        public BackInfo CheckSulphuricAcidByInfo1([FromForm] string plate, [FromForm] string strGCompany, [FromForm] string strYCompany)
        {
            //说明：2022年12月30日,如果为市外的话，用购买备案号与运输单位来确定运输备案号
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            bi.code = 500;
            GPutOnRecord serch = new GPutOnRecord();
            serch.Enable = true;
            try
            {
                #region 查看购买备案信息
                //01 条件一个收货单位肯定只对应一个正在启用的购买备案号信息
                var db = DbHelper.GetDbConn();
                var temp = db.Queryable<GPutOnRecord>().Where(it => it.Enable == serch.Enable && it.GCompany == strGCompany).ToList();
                if (temp == null || temp.Count == 0)
                {
                    bi.code = 201;
                    bi.data = "1";
                    bi.message = "所选收货单位,未查询到购买备案号信息不能制卡";
                    return bi;
                }
                if (temp.Count > 1)
                {
                    bi.code = 201;
                    bi.data = "2";
                    bi.message = "所选收货单位,有多条正在启用的购买备案号信息";
                    return bi;
                }
                if (temp.Exists(it=>it.EndDate < System.DateTime.Now))
                {
                    bi.code = 201;
                    bi.data = "3";
                    bi.message = "所选收货单位,购买备案信息已过期";
                    return bi;
                }
                //还可以判断钱数与重量
                if (temp[0].GBalance <= 0)
                {
                    bi.code = 201;
                    bi.data = "4";
                    bi.message = "所选收货单位,购买备案信息账户总额不足";
                    return bi;
                }
                if (temp[0].RemainingWeight <= 0)
                {
                    bi.code = 201;
                    bi.data = "5";
                    bi.message = "所选收货单位,购买备案信息剩余重量不足";
                    return bi;
                }
                #endregion
                if (temp[0].InCity)
                {
                    #region 市内只有购买备案号
                    if (CheckStringExit(temp[0].PlateList, plate))
                    {
                        bi.code = 200;
                        bi.data = "GNumber:" + temp[0].GNumber + "," + "YNumber:";
                        bi.message = "硫酸备案号信息验证通过";
                        return bi;
                    }
                    else
                    {
                        bi.code = 201;
                        bi.data = "6";
                        bi.message = "所选收货单位,购买备案信息下无此车辆信息";
                        return bi;
                    }
                    #endregion
                }
                else
                {
                    #region 市外需查询运输备案号
                    var YPutOnRecordList = db.Queryable<YPutOnRecord>().Where(it => it.Enable == serch.Enable && it.GNumber == temp[0].GNumber && it.YCompany == strYCompany).ToList();
                    if (YPutOnRecordList == null || YPutOnRecordList.Count == 0)
                    {
                        bi.code = 201;
                        bi.data = "7";
                        bi.message = "所选收货单位、运输单位,未查询到运输备案号信息不能制卡";
                        return bi;
                    }
                    if (YPutOnRecordList.Count > 1)
                    {
                        bi.code = 201;
                        bi.data = "8";
                        bi.message = "所选收货单位、运输单位,有多条正在启用的运输备案号信息";
                        return bi;
                    }
                    if (YPutOnRecordList.Exists(it => it.EndDate < System.DateTime.Now))
                    {
                        bi.code = 201;
                        bi.data = "9";
                        bi.message = "所选收货单位、运输单位,运输备案号信息已过期";
                        return bi;
                    }
                    if (YPutOnRecordList[0].RemainingWeight <= 0)
                    {
                        bi.code = 201;
                        bi.data = "10";
                        bi.message = "所选收货单位、运输单位,运输备案信息剩余重量不足";
                        return bi;
                    }

                    string strPlateList = YPutOnRecordList[0].PlateList;
                    if (CheckStringExit(YPutOnRecordList[0].PlateList, plate))
                    {
                        bi.code = 200;
                        bi.data = "GNumber:" + temp[0].GNumber + "," + "YNumber:" + YPutOnRecordList[0].YNumber;
                        bi.message = "硫酸备案号信息验证通过";
                        return bi;
                    }
                    else
                    {
                        bi.code = 201;
                        bi.data = "11";
                        bi.message = "所选收货单位、运输单位,备案信息下无此车辆信息";
                        return bi;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                logger.LogInformation(ex.ToString());
                bi.code = 500;
                bi.data = "";
                bi.message = "验证出错";
                logger.LogError("SSMachineController-->CheckSulphuricAcid:验证是否可以拉硫酸出错：" + ex.ToString());
                return bi;
            }
        }

        /// <summary>
        /// 根据车牌号及收货单位查询备案号信息
        /// </summary>
        /// <param name="plate">车牌号</param> 
        /// <param name="strGCompany">购买单位（即收货单位）</param>
        /// <param name="strYCompany">运输单位</param>
        /// <returns></returns>
        [HttpPost("CheckSulphuricAcidByInfo")]
        public BackInfo CheckSulphuricAcidByInfo([FromForm] string plate, [FromForm] string strGCompany, [FromForm] string strYCompany)
        {
            //说明：2022年12月30日,如果为市外的话，用购买备案号与运输单位来确定运输备案号
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            bi.code = 500;
            GPutOnRecord serch = new GPutOnRecord();
            serch.Enable = true;
            try
            {
                #region 查看购买备案信息
                //01 条件一个收货单位肯定只对应一个正在启用的购买备案号信息
                var db = DbHelper.GetDbConn();
                var temp = db.Queryable<GPutOnRecord>().Where(it => it.Enable == serch.Enable && it.GCompany == strGCompany).ToList();
                if (temp == null || temp.Count == 0)
                {
                    bi.code = 201;
                    bi.data = "1";
                    bi.message = "所选收货单位,未查询到购买备案号信息不能制卡";
                    return bi;
                }
                if (temp.Count > 1)
                {
                    bi.code = 201;
                    bi.data = "2";
                    bi.message = "所选收货单位,有多条正在启用的购买备案号信息";
                    return bi;
                }
                if (temp[0].EndDate < System.DateTime.Now||temp[0].StartDate > System.DateTime.Now)
                {
                    bi.code = 201;
                    bi.data = "3";
                    bi.message = "所选收货单位,购买备案信息不在有效期内";
                    return bi;
                }
                //还可以判断钱数与重量
                if (temp[0].GBalance <= 0 && (temp[0].EnableCheck??true))
                {
                    bi.code = 201;
                    bi.data = "4";
                    bi.message = "所选收货单位,购买备案信息账户总额不足";
                    return bi;
                }
                if (temp[0].RemainingWeight <= 0)
                {
                    bi.code = 201;
                    bi.data = "5";
                    bi.message = "所选收货单位,购买备案信息剩余重量不足";
                    return bi;
                }
                #endregion
                if (temp[0].InCity)
                {
                    #region 市内只有购买备案号
                    if (CheckStringExit(temp[0].PlateList, plate))
                    {
                        bi.code = 200;
                        bi.data = "GNumber:" + temp[0].GNumber + "," + "YNumber:";
                        bi.message = "硫酸备案号信息验证通过";
                        return bi;
                    }
                    else
                    {
                        bi.code = 201;
                        bi.data = "6";
                        bi.message = "所选收货单位,购买备案信息下无此车辆信息";
                        return bi;
                    }
                    #endregion
                }
                else
                {
                    #region 市外需查询运输备案号
                    var YPutOnRecordList = db.Queryable<YPutOnRecord>().Where(it => it.Enable == serch.Enable && it.GNumber == temp[0].GNumber).ToList();
                    if (YPutOnRecordList == null || YPutOnRecordList.Count == 0)
                    {
                        bi.code = 201;
                        bi.data = "7";
                        bi.message = "所选收货单位、运输单位,未查询到运输备案号信息不能制卡";
                        return bi;
                    }
                    //可能有多个运输备案号，故需要一个一个处理，看这个车牌号在不在里面，在则查到备案信息，不在则提示没有
                    int index = -1;
                    for (int j = 0; j < YPutOnRecordList.Count; j++)
                    {
                        //也就是在这几个运输备案号中，车牌只会存在某一个运输备案号下面
                        if (CheckStringExit(YPutOnRecordList[j].PlateList, plate))
                        {
                            index = j;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        bi.code = 201;
                        bi.data = "11";
                        bi.message = "所选收货单位、运输单位,备案信息下无此车辆信息";
                        return bi;
                    }
                    if (YPutOnRecordList[index].EndDate < System.DateTime.Now || YPutOnRecordList[index].StartDate > System.DateTime.Now)
                    {
                        bi.code = 201;
                        bi.data = "9";
                        bi.message = "所选收货单位、运输单位所属运输备案号不在有效期内";
                        return bi;
                    }
                    if (YPutOnRecordList[index].RemainingWeight <= 0)
                    {
                        bi.code = 201;
                        bi.data = "10";
                        bi.message = "所选收货单位、运输单位,运输备案信息剩余重量不足";
                        return bi;
                    }

                    bi.code = 200;
                    bi.data = "GNumber:" + YPutOnRecordList[index].GNumber + "," + "YNumber:" + YPutOnRecordList[index].YNumber;
                    bi.message = "硫酸备案号信息验证通过";
                    return bi;
                    #endregion
                }
            }
            catch (Exception ex)
            {
                logger.LogInformation(ex.ToString());
                bi.code = 500;
                bi.data = "";
                bi.message = "验证出错";
                logger.LogError("SSMachineController-->CheckSulphuricAcid:验证是否可以拉硫酸出错：" + ex.ToString());
                return bi;
            }
        }


        /// <summary>
        /// 逗号分隔的每一项里是否存在所给字符串
        /// </summary>
        /// <param name="Str">逗号分隔的字符串</param>
        /// <param name="Target">目标项</param>
        /// <returns></returns>
        private bool CheckStringExit(string Str, string Target)        
        {
            try
            {
                if (string.IsNullOrEmpty(Str)|| string.IsNullOrEmpty(Target))
                {
                    return false;
                }
                List<string> array = Str.Split(',').ToList<string>();
                if (array != null && array.Exists(it => it == Target))
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                logger.ErrorModel(nameof(SSMachineController) + "-" + nameof(CheckStringExit), ex);//保存到数据库里
            }
            return false;
        }

        #endregion

        //2023年1月12日09:19:35 测试换 gitee 帐号后的代码上传

        #region 2023年9月25日 接口测试
        //
        //
        /// <summary>
        /// 门禁出出人口信上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost("QueryDoorControlRemote")]
        public BackInfo QueryDoorControlRemote(DoorControlRemote str)
        {
            //说明：2022年12月30日,如果为市外的话，用购买备案号与运输单位来确定运输备案号
            var jsn = new JObject();
            BackInfo bi = new BackInfo();
            bi.code = 500;
            GPutOnRecord serch = new GPutOnRecord();
            serch.Enable = true;
            try
            {
                bi.code = 200;
                bi.data = "GNumber:";
                bi.message = "硫酸备案号信息验证通过";
                return bi;
            }
            catch (Exception ex)
            {
                logger.LogInformation(ex.ToString());
                bi.code = 500;
                bi.data = "";
                bi.message = "验证出错";
                logger.LogError("SSMachineController-->CheckSulphuricAcid:验证是否可以拉硫酸出错：" + ex.ToString());
                return bi;
            }
        }


        //
        //
        /// <summary>
        /// 查询车辆信息接口
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetAppointmentInfoByQrCode")]
        public BackInfo_DoorContolByQrCode GetAppointmentInfoByQrCode(string qrCode)
        {
            //说明：2022年12月30日,如果为市外的话，用购买备案号与运输单位来确定运输备案号
            var jsn = new JObject();
            BackInfo_DoorContolByQrCode bi = new BackInfo_DoorContolByQrCode();
            bi.code = 500;
            GPutOnRecord serch = new GPutOnRecord();
            serch.Enable = true;
            try
            {
                bi.code = 200;
                //bi.data = new AppointmentInfoModel();
                //bi.data.driverName = "张三";
                bi.data = null;
                bi.message = "硫酸备案号信息验证通过";
                return bi;
            }
            catch (Exception ex)
            {
                logger.LogInformation(ex.ToString());
                bi.code = 500;
                bi.data = new AppointmentInfoModel();
                bi.message = "验证出错";
                logger.LogError("SSMachineController-->CheckSulphuricAcid:验证是否可以拉硫酸出错：" + ex.ToString());
                return bi;
            }
        }
        #endregion
    }
}
